package org.gitos.test.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.gitos.cloud.domain.tcp.Bucket;
import org.gitos.cloud.domain.tcp.DeviceId;

/**
 * Created by shizhengchu on 16/3/10.
 */
public class ClientLed {

    public static void main(String[] args) {

        String remoteIp = "192.168.0.129";
//        String remoteIp = "119.28.7.26";

        Bucket bucket = new Bucket();
        EventLoopGroup group = new NioEventLoopGroup();
        Channel ch;
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class).handler(new InitHandler());

            ch = bootstrap.connect(remoteIp, 8999).sync().channel();
            // Read commands from the stdin.
            ChannelFuture lastWriteFuture = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            for (; ; ) {
                String line = in.readLine();
                if (line == null) {
                    break;
                }
                bucket.setCmd((short) 0x1101);
                bucket.setContent(line.getBytes());
                bucket.setDeviceId(DeviceId.instance("AAAAAA".getBytes()));
                // Sends the received line to the server.
                lastWriteFuture = ch.writeAndFlush(bucket);

                // If user typed the 'bye' command, wait until the server closes
                // the connection.
                if ("bye".equals(line.toLowerCase())) {
                    ch.closeFuture().sync();
                    break;
                }
            }

            // Wait until all messages are flushed before closing the channel.
            if (lastWriteFuture != null) {
                lastWriteFuture.sync();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}

class InitHandler extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pip = ch.pipeline();

        pip.addLast("LoggingHandler", new LoggingHandler(LogLevel.INFO));
        pip.addLast("LengthFieldBasedFrameDecoder", new LengthFieldBasedFrameDecoder(65539, 0, 2, -2, 0));
        pip.addLast("TcpDecoder", new TcpDecoder());
        pip.addLast("TcpEncoder", new TcpEncoder());

    }
}
